package com.ruoyi.framework.datasource;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DatabaseUtil {
    private static final Logger log = LoggerFactory.getLogger(DatabaseUtil.class);

    public static void createDatabase(DataSource dataSource) {
        String url = ((DruidDataSource) dataSource).getUrl();
        String driverClassName = ((DruidDataSource) dataSource).getDriverClassName();
        String username = ((DruidDataSource) dataSource).getUsername();
        String password = ((DruidDataSource) dataSource).getPassword();

        String databaseName = "";
        String jdbcUrl = "";

        String pattern = "(.*//[\\w\\-.]+:\\d+)/(\\w+)";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(url);

        if (m.find()) {
            // 匹配到结果
            jdbcUrl = m.group(1);
            databaseName = m.group(2);
        }

        if (StringUtils.isEmpty(databaseName)) {
            log.error("未获取到数据库名称");
            return;
        }

        Connection connection = null;
        Statement statement = null;

        try {
            // 加载驱动程序
            Class.forName(driverClassName);

            // 建立数据库连接
            connection = DriverManager.getConnection(jdbcUrl, username, password);

            // 创建 Statement 对象
            statement = connection.createStatement();

            // 创建数据库
            String sql = "CREATE DATABASE IF NOT EXISTS " + databaseName;
            statement.executeUpdate(sql);
        } catch (ClassNotFoundException | SQLException e) {
            log.error("创建数据库失败：", e);
        } finally {
            IoUtil.close(statement);
            IoUtil.close(connection);
        }

    }

    public static void createTable(DataSource dataSource) {
        try {
            String catalog = dataSource.getConnection().getCatalog();
            if (!hasInit(dataSource, catalog)) {
                log.info("数据初始化开始: " + DateUtil.now());
                Resource resources = new ClassPathResource("sql/ry_sso.sql");
                Resource quartzResources = new ClassPathResource("sql/quartz.sql");
                ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
                resourceDatabasePopulator.addScripts(resources, quartzResources);
                resourceDatabasePopulator.execute(dataSource);
                log.info("数据初始化结束: " + DateUtil.now());
            }
        } catch (SQLException e) {
            log.error("数据库连接失败");
        }
    }

    private static boolean hasInit(DataSource dataSource, String databaseName) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        try {
            String sql = "SELECT COUNT(1) FROM information_schema.tables WHERE table_schema = ?";
            Integer count = jdbcTemplate.queryForObject(sql, Integer.class, databaseName);
            if (count != null) {
                return count > 0;
            }
        } catch (DataAccessException e) {
            String sql = "show tables";
            List<String> tableNames = jdbcTemplate.queryForList(sql, String.class);
            return tableNames.size() > 0;
        }

        return false;
    }

}